import datetime
import json
import random
import time
import traceback
import requests
from django.http import HttpResponse
import logging

from common import models

logger = logging.getLogger('log')

cookies_list = [
    'agbsid=pu-_1aZZRwnkRVi1hPOv-uPqRCmkA6HkMkEtp2dxcRcum9RE_7518LJy0sPSJqiFFjKvUkiBbffJzA0GCuek0A; logan_session_token=wbknj2q9060k0xwg9or5;'
]


def spider_hotel_list(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        page = params.get("page", 1)
        page_size = params.get("pageSize", 10)
        cookie = params.get('cookie','')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        else:
            url = "https://tongzhou.meituan.com/api/agent/v1/vpoi/info/searchpoi"
            payload = {
                'optimus_code': 10,
                'optimus_risk_level': 71,
                'optimus_uuid': 131715960,
                'enabled': True,
                'poiName': '',
                'yodaReady': 'h5',
                'csecplatform': 4,
                'csecversion': '2.2.1',
                'pageNo': page,
                'pageSize': page_size
            }
            headers = {
                'Accept': 'application/json, text/plain, */*',
                'Accept-Encoding': 'gzip, deflate, br',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Connection': 'keep-alive',
                'Cookie': cookie,
                'Referer': 'https://tongzhou.meituan.com/poi/index.html',
                'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"Windows"',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/117.0',
                'X-Requested-With': 'XMLHttpRequest'
            }
            rsp = requests.get(url, headers=headers, params=payload)
            if rsp.status_code == 200:
                mt_rsp = rsp.json()
                status = mt_rsp.get('status', -1)
                message = mt_rsp.get('message', '')
                if status == 0:
                    mt_rsp_data = mt_rsp.get('data')
                    hotels = mt_rsp_data.get('data', [])
                    # hotel_list = []
                    # for item in hotels:
                    #     hotel_id = item.get('poiId', -1)
                    #     if hotel_id == -1:
                    #         continue
                    #     hotel = {
                    #         'hotelId': hotel_id,
                    #         'hotelName': item.get('name', ''),
                    #         'cityId': item.get('cityId', -1),
                    #         'cityName': item.get('cityName', ''),
                    #         'regionId': item.get('locationId', ''),
                    #         'regionName': item.get('locationName', ''),
                    #         'address': item.get('address', ''),
                    #         'phone': item.get('phone', ''),
                    #         'status': item.get('serviceStatus', 1),
                    #         # 0 国家旅游局颁布五星级证书
                    #         # 1 豪华（按五星级标准建造）
                    #         # 2 国家旅游局颁布四星级证书
                    #         # 3 高档（按四星级标准建造）
                    #         # 4 国家旅游局颁布三星级证书
                    #         # 5 舒适型（按三星级标准建造）
                    #         # 6 经济型
                    #         # 7 低档
                    #         'star': item.get('rating', 0)
                    #     }
                    #     hotel_list.append(hotel)
                    response.success('请求成功', hotels)
                else:
                    response.error(0, '美团接口返回失败，内容：' + message)
            else:
                response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_hotel_room_list(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        hotel_id = params.get("hotelId", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        else:
            if hotel_id is None:
                response.error(0, '酒店ID不允许为空')
            else:
                url = "https://tongzhou.meituan.com/api/agent/v1/vpoi/goods/poiId" + str(hotel_id) + "/prepayGoodsList?"
                payload = {
                    'optimus_code': 10,
                    'optimus_risk_level': 71,
                    'optimus_uuid': 131715960,
                    'yodaReady': 'h5',
                    'csecplatform': 4,
                    'csecversion': '2.2.1',
                    'startDate': time.strftime("%Y-%m-%d"),
                    'endDate': (datetime.datetime.now() + datetime.timedelta(days=6)).strftime('%Y-%m-%d')
                }
                headers = {
                    'Accept': 'application/json',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Connection': 'keep-alive',
                    'Cookie': cookie,
                    'Referer': 'https://tongzhou.meituan.com/pregoods/index.html?',
                    'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
                    'sec-ch-ua-mobile': '?0',
                    'sec-ch-ua-platform': '"Windows"',
                    'Sec-Fetch-Dest': 'empty',
                    'Sec-Fetch-Mode': 'cors',
                    'Sec-Fetch-Site': 'same-origin',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/117.0',
                    'x-Requested-With': 'XMLHttpRequest'
                }
                rsp = requests.get(url, headers=headers, params=payload)
                if rsp.status_code == 200:
                    mt_rsp = rsp.json()
                    status = mt_rsp.get('status', -1)
                    message = mt_rsp.get('message', '')
                    if status == 0:
                        mt_rsp_data = mt_rsp.get('data')
                        goods = mt_rsp_data.get('goods', [])
                        response.success('请求成功', goods)
                    else:
                        response.error(0, '美团接口返回失败，内容：' + message)
                else:
                    response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_get_price_ratio(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        partner_id = params.get("partnerId", None)
        base_price = params.get("basePrice", None)
        poi_id = params.get("poiId", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif partner_id is None:
            response.error(0, 'PartnerId不允许为空')
        elif poi_id is None:
            response.error(0, '酒店ID不允许为空')
        elif base_price is None:
            response.error(0, '价格不允许为0')
        else:
            url = "https://tongzhou.meituan.com/api/agent/v1/vpoi/goods/getPriceInfoByBaseAdvanceRatio?"
            params = {
                'optimus_code': 10,
                'optimus_risk_level': 71,
                'optimus_uuid': 131715960,
            }
            payload = {
                'basePrice': base_price,
                'partnerId': partner_id,
                'poiId': poi_id
            }
            headers = {
                'Accept': 'application/json',
                'Accept-Encoding': 'gzip, deflate, br',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Connection': 'keep-alive',
                'Cookie': cookie,
                'Referer': 'https://tongzhou.meituan.com/pregoods/index.html?',
                'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"Windows"',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
                'x-Requested-With': 'XMLHttpRequest'
            }
            rsp = requests.post(url, headers=headers, params=params, data=json.dumps(payload, ensure_ascii=False))
            if rsp.status_code == 200:
                mt_rsp = rsp.json()
                status = mt_rsp.get('status', -1)
                success = mt_rsp.get("success", False)
                if status == 200 and success:
                    mt_rsp_data = mt_rsp.get('data')
                    response.success('请求成功', mt_rsp_data)
                else:
                    response.error(0, '美团接口返回失败，status：' + str(status))
            else:
                response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_submit_update_price(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        price_info = params.get('priceInfo', None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif price_info is None:
            response.error(0, '价格参数不允许为空')
        else:
            url = "https://tongzhou.meituan.com/api/agent/v1/goods/batchUpdatePriceAndRelationRules"
            params = {
                'optimus_code': 10,
                'optimus_risk_level': 71,
                'optimus_uuid': 131715960,
                'yodaReady': 'h5',
                'csecplatform': 4,
                'csecversion': '2.2.1',
            }
            headers = {
                'Accept': 'application/json',
                'Accept-Encoding': 'gzip, deflate, br',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Connection': 'keep-alive',
                'Cookie': cookie,
                'Referer': 'https://tongzhou.meituan.com/pregoods/index.html?',
                'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"Windows"',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
                'x-Requested-With': 'XMLHttpRequest'
            }
            try:
                rsp = requests.post(url, headers=headers, params=params,
                                    data=json.dumps(price_info, ensure_ascii=False).encode('utf-8'))
                if rsp.status_code == 200:
                    mt_rsp = rsp.json()
                    status = mt_rsp.get('status', -1)
                    message = mt_rsp.get('message', '')
                    if status == 0:
                        mt_rsp_data = mt_rsp.get('data')
                        url = "https://tongzhou.meituan.com/api/agent/v1/vpoi/goods/getProcessRate/" + mt_rsp_data + "?"
                        rsp = requests.get(url, headers=headers, params=params)
                        if rsp.status_code == 200:
                            mt_rsp = rsp.json()
                            status = mt_rsp.get('status', -1)
                            message = mt_rsp.get('message', '')
                            if status == 0:
                                price_info["createFlag"] = True
                                url = "https://tongzhou.meituan.com/api/agent/v1/goods/batchUpdatePriceAndRelationRules"
                                rsp = requests.post(url, headers=headers, params=params,
                                                    data=json.dumps(price_info, ensure_ascii=False).encode('utf-8'))
                                if rsp.status_code == 200:
                                    mt_rsp = rsp.json()
                                    status = mt_rsp.get('status', -1)
                                    message = mt_rsp.get('message', '')
                                    if status == 0:
                                        mt_rsp_data = mt_rsp.get('data')
                                        url = "https://tongzhou.meituan.com/api/agent/v1/vpoi/goods/getProcessRate/" + mt_rsp_data + "?"
                                        rsp = requests.get(url, headers=headers, params=params)
                                        if rsp.status_code == 200:
                                            mt_rsp = rsp.json()
                                            status = mt_rsp.get('status', -1)
                                            message = mt_rsp.get('message', '')
                                            if status == 0:
                                                response.success('提交成功', '')
                                            else:
                                                response.error(0, '美团接口返回失败，内容：' + message)
                                        else:
                                            response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
                                    else:
                                        response.error(0, '美团接口返回失败，内容：' + message)
                            else:
                                response.error(0, '美团接口返回失败，内容：' + message)
                        else:
                            response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
                    else:
                        response.error(0, '美团接口返回失败，内容：' + message)
                else:
                    response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
            except Exception as e:
                logger.error(traceback.format_exc())
                response.error(0, "请求美团接口失败：error= %s" % e)
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_submit_update_inventory(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        hotel_id = params.get('hotelId', None)
        inventory_info = params.get("inventory", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif inventory_info is None:
            response.error(0, '房态参数不允许为空')
        else:
            url = "https://tongzhou.meituan.com/api/agent/v1/vpoi/goods/poiId/" \
                  + str(hotel_id) + "/batchUpdateInventory?"
            params = {
                'optimus_code': 10,
                'optimus_risk_level': 71,
                'optimus_uuid': 131715960,
                'yodaReady': 'h5',
                'csecplatform': 4,
                'csecversion': '2.2.1',
            }
            headers = {
                'Accept': 'application/json',
                'Accept-Encoding': 'gzip, deflate, br',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Connection': 'keep-alive',
                'Cookie': cookie,
                'Referer': 'https://tongzhou.meituan.com/pregoods/index.html?',
                'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"Windows"',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
                'x-Requested-With': 'XMLHttpRequest'
            }
            try:
                rsp = requests.post(url, headers=headers, params=params,
                                    data=json.dumps(inventory_info, ensure_ascii=False).encode('utf-8'))
                if rsp.status_code == 200:
                    mt_rsp = rsp.json()
                    status = mt_rsp.get('status', -1)
                    message = mt_rsp.get('message', '')
                    if status == 0:
                        mt_rsp_data = mt_rsp.get('data')
                        response.success('请求成功', mt_rsp_data)
                    else:
                        response.error(0, '美团接口返回失败，内容：' + message)
                else:
                    response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
            except Exception as e:
                logger.error(traceback.format_exc())
                response.error(0, "请求美团接口失败：error= %s" % e)
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_batch_update_rate_plan(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        hotel_id = params.get('hotelId', None)
        rate_plan_list = params.get("ratePlanList", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif rate_plan_list is None:
            response.error(0, '房态参数不允许为空')
        else:
            url = "https://tongzhou.meituan.com/api/agent/v1/poi/" \
                  + str(hotel_id) + "/goods/batchUpdateRpRules?"
            params = {
                'optimus_code': 10,
                'optimus_risk_level': 71,
                'optimus_uuid': 131715960,
            }
            headers = {
                'Accept': 'application/json',
                'Accept-Encoding': 'gzip, deflate, br',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Connection': 'keep-alive',
                'Cookie': cookie,
                'Referer': 'https://tongzhou.meituan.com/pregoods/index.html?',
                'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
                'sec-ch-ua-mobile': '?0',
                'Content-Type': 'application/json',
                'sec-ch-ua-platform': '"Windows"',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
                'x-Requested-With': 'XMLHttpRequest'
            }
            rsp = requests.put(url, headers=headers, params=params,
                               data=json.dumps(rate_plan_list, ensure_ascii=False).encode('utf-8'))
            if rsp.status_code == 200:
                mt_rsp = rsp.json()
                status = mt_rsp.get('status', -1)
                message = mt_rsp.get('message', '')
                if status == 0:
                    mt_rsp_data = mt_rsp.get('data')
                    response.success('请求成功', mt_rsp_data)
                else:
                    response.error(0, '美团接口返回失败，内容：' + message)
            else:
                response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_get_order_list(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        order_id = params.get('orderId', None)
        start_date = params.get('startDate', None)
        end_date = params.get('endDate', None)
        page = params.get('page', None)
        page_size = params.get("pageSize", None)
        status = params.get("status", 0)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif start_date is None or end_date is None:
            response.error(0, '开始/结束时间不允许为空')
        else:
            url = "https://tongzhou.meituan.com/api/agent/v2/order/apt/orders?yodaReady=h5&csecplatform=4&csecversion=3.0.0"

            payload = {
                "pageSize": page_size,
                "pageNo": page,
                "dateFilter": {
                    "searchTimeType": 2,
                    "startDate": start_date,
                    "endDate": end_date
                },
                "roomFilter": {
                    "cityId": "",
                    "roomId": [],
                    "poiId": ""
                },
                "userFilter": {
                    "checkInName": ""
                },
                "orderFilter": {
                    "orderId": order_id,
                    "status": status,
                    "type": [
                        1,
                        4
                    ],
                    "hotelSourceOrderId": "",
                    "bizTag": 0,
                    "sendStatus": 0,
                    "sendCallbackStatus": 0
                },
                "sort": {
                    "sortField": 2,
                    "sortType": 2
                }
            }

            headers = {
                'Accept': 'application/json',
                'Accept-Encoding': 'gzip, deflate, br',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Connection': 'keep-alive',
                'Cookie': cookie,
                'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
                'sec-ch-ua-mobile': '?0',
                'Content-Type': 'application/json',
                'sec-ch-ua-platform': '"Windows"',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
                'x-Requested-With': 'XMLHttpRequest'
            }
            rsp = requests.post(url, headers=headers, data=json.dumps(payload, ensure_ascii=False).encode('utf-8'))
            if rsp.status_code == 200:
                mt_rsp = rsp.json()
                status = mt_rsp.get('status', -1)
                message = mt_rsp.get('message', '')
                if status == 0:
                    mt_rsp_data = mt_rsp.get('data')
                    response.success('请求成功', mt_rsp_data)
                else:
                    response.error(0, '美团接口返回失败，内容：' + message)
            else:
                response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')

def spider_get_order_user_history(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        order_id = params.get('orderId', None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        else:
            url = "https://tongzhou.meituan.com/api/agent/v2/orders/"+order_id+"/userHistory?yodaReady=h5&csecplatform=4&csecversion=3.2.0"

            headers = {
                'Accept': 'application/json',
                'Accept-Encoding': 'gzip, deflate, br',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Connection': 'keep-alive',
                'Cookie': cookie,
                'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
                'sec-ch-ua-mobile': '?0',
                'Content-Type': 'application/json',
                'sec-ch-ua-platform': '"Windows"',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
                'x-Requested-With': 'XMLHttpRequest'
            }
            rsp = requests.get(url, headers=headers)
            if rsp.status_code == 200:
                mt_rsp = rsp.json()
                status = mt_rsp.get('status', -1)
                message = mt_rsp.get('message', '')
                if status == 0:
                    mt_rsp_data = mt_rsp.get('data')
                    response.success('请求成功', mt_rsp_data)
                else:
                    response.error(0, '美团接口返回失败，内容：' + message)
            else:
                response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')
